<template>
  <div>
    <!-- 搜索框 -->
    <form action="/">
      <van-search
        background="#3296fa"
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isShowResult=false"
      >
      </van-search>
    </form>
    <!-- 搜索结果 -->
    <search-result
      v-if="isShowResult"
      :searchText="searchText"
    ></search-result>
    <!-- 搜索建议 -->
    <search-suggestion
      @search="onSearch"
      v-else-if="searchText"
      :searchText="searchText"
    ></search-suggestion>
    <!-- 搜索历史 -->
    <search-history
      v-else
      @search="onSearch"
    ></search-history>
  </div>
</template>
<script>
import searchHistory from './components/search-history.vue'
import searchResult from './components/search-result.vue'
import searchSuggestion from './components/search-suggestion.vue'
import { setItem, getItem } from '@/utils/storage.js'
import { uniq } from 'lodash'

export default {
  data () {
    return {
      searchText: '',
      isShowResult: false,
      searchTextList: getItem('searchHistory') || []
    }
  },
  methods: {
    onSearch (text) {
      this.searchText = text
      this.isShowResult = true
      this.searchTextList.push(this.searchText)
      this.searchTextList = uniq(this.searchTextList)
      setItem('searchHistory', this.searchTextList)
    },
    onCancel () {
      this.$router.back()
    }
  },
  components: {
    searchHistory,
    searchResult,
    searchSuggestion
  }
}
</script>
<style lang="less" scoped>
.van-search__action {
  color: #ffffff;
}
</style>
